package com.thinkTank.oa.perm;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import com.thinkTank.oa.util.MD5Util;

/***
 * 自定义用户认证逻辑
 * 继承WebSecurityConfigurerAdapter，并重写它的方法来设置一些web安全的细节
 * @author dq
 *
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private DataSource dataSource;
	@Bean
	public PersistentTokenRepository persistentTokenRepository() {
	    JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
	    // 配置数据源
	    jdbcTokenRepository.setDataSource(dataSource);
	    // 第一次启动的时候自动建表（可以不用这句话，自己手动建表，源码中有语句的）
	   //jdbcTokenRepository.setCreateTableOnStartup(true);
	    return jdbcTokenRepository;
	}
	
    /**
     * 自定义验证
     * 通过 实现UserDetailService 来进行验证
     */
    @Autowired
    private MyCustomUserService myCustomUserService;

    /**
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{

    	//System.out.println("333333333333333333333333");
        //校验用户
    	 auth.userDetailsService(myCustomUserService)
    	//校验密码
    	 .passwordEncoder(new PasswordEncoder() {
			
    		  @Override
              public String encode(CharSequence rawPassword) {
    			 // System.out.println("4444444444444444444");
                  return MD5Util.MD5(String.valueOf(rawPassword));
              }

              @Override
              public boolean matches(CharSequence rawPassword, String encodedPassword) {
            	 // System.out.println("555555555555555555555");
                  return encodedPassword.equals(MD5Util.MD5(String.valueOf(rawPassword)));
              }
          
        });
    }
    @Bean
    public LoginSuccessHandler loginSuccessHandler() {
        return new LoginSuccessHandler();
    }
    /**
     * 创建自定义的表单
     *
     * 页面、登录请求、跳转页面等
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/getImage","/showAddDemand","/addDemand","/","/login","/css/**","/js/**","/plugins/layx/layx.min.js",
                		"/**/*.css","/**/*.js","/**/*.jpg","/getCityByProvinceId/*","/getAreaByCityId/*",
                		"/**/*.woff2","/**/*.png","/**/*.ico")//允许访问
                .permitAll()
              //其他地址的访问均需验证权限
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")//拦截后get请求跳转的页面
                .defaultSuccessUrl("/index")
                .permitAll().successHandler(loginSuccessHandler()).failureHandler(new MyAuthenctiationFailureHandler())
                .and().rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(1000*60*60*360).and()
                .logout().logoutUrl("/loginOut")
                .logoutSuccessUrl("/login")
                .permitAll();
    }
//    .formLogin()
//    .loginPage( "/login")
//     .usernameParameter("uname")//自定义用户名参数名称
//    .passwordParameter("pwd")//自定义密码参数名称
}

